package cn.org.mrliu.ssm.qq.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QQConfigUtil {
	private static final Logger log = LoggerFactory.getLogger(QQConfigUtil.class);

	private QQConfigUtil() {

	}

	static {
		parse();
	}

	public static QQConfig getConfig() {

		return QQConfig.getInstance();
	}

	private static Properties getProperties() {
		InputStream inputStream = QQConfigUtil.class.getClassLoader().getResourceAsStream("qq.properties");
		if (inputStream == null) {
			throw new RuntimeException("没有找到qq.properties配置文件");
		}
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
			log.debug("加载qq.properties配置文件成功");
		} catch (IOException e) {
			log.error("加载qq.properties配置文件失败");
			e.printStackTrace();
			throw new RuntimeException("加载qq.properties配置文件错误");
		}
		return properties;
	}

	private static void parse() {
		Properties properties = getProperties();
		QQConfig config = QQConfig.getInstance();
		// qqApi接口
		String qqApi = properties.getProperty("qqApi");
		if (qqApi == null || qqApi.trim().length() == 0) {
			throw new RuntimeException("qq.properties文件中未设置qqApi的值");
		}
		log.debug("qqApi:" + qqApi);
		config.setQqApi(qqApi);
		// 发送间隔
		String sendIntervalString = properties.getProperty("sendInterval");
		if (sendIntervalString != null && sendIntervalString.trim().length() > 0) {
			config.setSendInterval(Integer.valueOf(sendIntervalString));
		}
		log.debug("sendInterval:" + sendIntervalString);
		// 连接超时
		String connectTimeoutString = properties.getProperty("connectTimeout");
		if (connectTimeoutString != null && connectTimeoutString.trim().length() > 0) {
			config.setConnectTimeout(Integer.valueOf(connectTimeoutString));
		}
		log.debug("connectTimeout:" + connectTimeoutString);
		// 读取超时
		String readTimeoutString = properties.getProperty("readTimeout");
		if (readTimeoutString != null && readTimeoutString.trim().length() > 0) {
			config.setReadTimeout(Integer.valueOf(readTimeoutString));
		}
		log.debug("readTimeout:" + readTimeoutString);
		// QQ消息内容编码
		config.setEncoding(properties.getProperty("encoding", "UTF-8"));
		log.debug("encoding:" + config.getEncoding());
		// 队列最大值
		String queueMaxSizeString = properties.getProperty("queueMaxSize");
		if (queueMaxSizeString != null && queueMaxSizeString.trim().length() > 0) {
			config.setQueueMaxSize(Integer.valueOf(queueMaxSizeString));
		}
		log.debug("queueMaxSize:" + queueMaxSizeString);

	}

}
